import { map, mergeMap, retryWhen, zip } from "rxjs/operators";
import { range, timer, Observable } from "rxjs";
import { Fun1 } from "../type/fun";

export const backoff = (
  maxTries: number,
  ms: number
): Fun1<Observable<any>> => {
  return obs$ => {
    return obs$.pipe(
      retryWhen(attempts =>
        range(1, maxTries).pipe(
          zip(attempts, i => i),
          map(i => i * i),
          mergeMap(i => timer(i * ms))
        )
      )
    );
  };
};
